/**
 * 问题库
 */
import React, { Component } from "react";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import { Card, Button, Modal, Table, Input, Divider, message } from "antd";
import styles from './knowledgeGather.less';
import { postGenerateQuestionsDel, getSimilarQuestionsList, postSimilarQuestionsAdd, cancelKnowledgeCollect } from '@/services/knowledgeGather';

class SimilarQuestion extends Component {
    constructor(props) {
        super(props);
        this.state = {
            content: '',
            list: [],
            total: 0,
            queryData: {
                current: 1,
                size: 10,
            },
            selectedRowKeys: [],
            cancelLoading: false,
            tableLoading: false,
        };
    }

    componentDidMount() {
        this.getSimilarQaList();
    }

    getSimilarQaList = () => {
        const { location: { query: { questionId, question } } } = this.props;
        const { queryData } = this.state;
        queryData.questionId = questionId;
        this.setState({ tableLoading: true }, async () => {
            let res = await getSimilarQuestionsList(queryData);
            console.log(res);
            this.setState({ tableLoading: false, list: res.records, total: res.total, content: decodeURI(question) });
        })
    }

    setSimilarQaList = () => {
        let { queryData } = this.state;
        queryData.current = 1;
        this.setState({ queryData }, () => this.getSimilarQaList());
    }

    onSelectChange = selectedRowKeys => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.setState({ selectedRowKeys });
    };

    changePage = (page, size) => {
        let { queryData } = this.state;
        queryData.current = page;
        queryData.size = size;
        this.setState({ queryData }, () => this.getSimilarQaList());
    }

    removeQuestion = id => {
        const that = this;
        Modal.confirm({
            title: '是否确定删除该问题',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                let res = await postGenerateQuestionsDel({ ids: [id] });
                console.log(res);
                if (res.code === 0) {
                    message.success("操作成功");
                    that.setSimilarQaList();
                }
            },
            onCancel() {
                console.log('取消删除！！！');
            },
        });
    };

    removeQuestionList = () => {
        const that = this;
        const { selectedRowKeys } = this.state;

        Modal.confirm({
            title: '是否确定删除这些问题',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                let res = await postGenerateQuestionsDel({ ids: selectedRowKeys });
                console.log(res);
                if (res.code === 0) {
                    message.success("操作成功");
                    that.setState({ selectedRowKeys: [] }, () => that.setSimilarQaList());
                }
            },
            onCancel() {
                console.log('取消删除！！！');
            },
        });
    }

    similarQuestion = async row => {
        const { location: { query: { questionId } } } = this.props;
        let obj = {
            questionId,
            questionIdList: [row.id],
        };
        let res = await postSimilarQuestionsAdd(obj);
        console.log(res);
        if (res.code == 0) {
            this.getSimilarQaList();
        }
    }

    similarQuestionList = async () => {
        const { location: { query: { questionId } } } = this.props;
        const { selectedRowKeys } = this.state;
        let obj = {
            questionId,
            questionIdList: selectedRowKeys,
        };
        let res = await postSimilarQuestionsAdd(obj);
        console.log(res);
        if (res.code == 0) {
            this.getSimilarQaList();
        }
    }

    render() {
        const { list, queryData, total, selectedRowKeys, content, cancelLoading } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const columns = [
            {
                title: '标准问',
                dataIndex: 'content',
                key: 'content',
            },
            {
                title: '相似度',
                dataIndex: 'score',
                key: 'score',
                width: 160,
                align: 'center',
                render: text => {
                    if (text) {
                        return ((text.toFixed(2)) * 1000 / 10) + '%';
                    }
                }
            },
            {
                title: '操作',
                width: 300,
                align: 'center',
                render: (text, row, index) => {
                    return (
                        <div style={{ display: 'flex', gap: '20px', justifyContent: 'center' }}>
                            <Button type="danger" onClick={() => this.removeQuestion(row.id)} style={{ width: '120px' }}>删除</Button>
                            <Button type="primary" onClick={() => this.similarQuestion(row)} style={{ width: '120px', marginRight: 10 }}>添加为相似问</Button>
                        </div>
                    );
                },
            },
        ];
        let sapnClass = {
            width: 240, marginRight: 16,
            // border: '1px solid #d9d9d9',
            // borderRadius: '4px',
            padding: '5px 11px',
            fontSize: '18px',
            fontWeight: 'bold',
        };

        return (
            <div className={styles['question-library']}>
                <Card bordered={false}>
                    <div className={styles.top}>
                        <Button onClick={this.backRouter} loading={cancelLoading}>取消采编</Button>
                        <Button type="primary" onClick={this.revertRouter}>返回列表</Button>
                    </div>
                    <Divider style={{ margin: '16px 0' }} />
                    <div className={styles.top}>
                        <div>
                            {content && content != '' ? <span style={sapnClass}>{content}</span> : null}
                        </div>
                        <div style={{ display: 'flex', gap: "20px" }}>
                            <Button type="primary" onClick={this.similarQuestionList}>批量添加相似问</Button>
                            <Button type="danger" onClick={this.removeQuestionList}>批量删除</Button>
                        </div>
                    </div>
                    <Table
                        rowKey="id"
                        bordered
                        columns={columns}
                        dataSource={list}
                        loading={this.state.tableLoading}
                        rowSelection={rowSelection}
                        pagination={{
                            current: queryData.current,
                            total: parseInt(total),
                            onChange: this.changePage,
                            showQuickJumper: true,
                            showSizeChanger: true,
                            onShowSizeChange: this.changePage,
                        }}
                    />
                </Card>
            </div>
        );
    }

    revertRouter = () => {
        const { dispatch } = this.props;
        let pathname = "/knowledgeDesign/knowledgeCollect/questionLibrary";
        dispatch(routerRedux.push({ pathname }));
    }

    backRouter = () => {
        Modal.confirm({
            title: '确定取消当前文档的采编',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                this.setState({ cancelLoading: true })
                let res = await cancelKnowledgeCollect();
                console.log(res);
                if (res.code === 0) {
                    this.setState({ cancelLoading: false })
                    const { dispatch } = this.props;
                    let pathname = "/knowledgeDesign/knowledgeCollect";
                    dispatch(routerRedux.push({ pathname }));
                } else {
                    this.setState({ cancelLoading: false })
                }
            },
            onCancel() {
                console.log('取消操作！！！');
            },
        });
    }
}

export default connect(({ user }) => ({
    currentUser: user.currentUser,
}))(SimilarQuestion);
